package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.entity.dto.OrdersDto;
import com.itheima.reggie.mapper.*;
import com.itheima.reggie.service.OrderService;
import com.itheima.reggie.utils.UUIDUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired(required = false)
    private OrderMapper orderMapper;

    @Autowired(required = false)
    private OrderDetailMapper orderDetailMapper;

    @Autowired(required = false)
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired(required = false)
    private UserMapper userMapper;

    @Autowired(required = false)
    private AddressBookMapper addressBookMapper;


    /**
     * 下单功能
     * @param orders
     * @param userId
     */
    @Override
    @Transactional
    public void submit(Orders orders, Long userId) {
//        A. 获得当前用户id, 查询当前用户的购物车数据
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(userId);

//        B. 根据当前登录用户id, 查询用户数据
        User user = userMapper.findById(userId);

//        C. 根据地址ID, 查询地址数据
        AddressBook addressBook = addressBookMapper.getById(orders.getAddressBookId());

        //订单的id
        Long orderId  = UUIDUtils.getUUIDInOrderId().longValue();

        //声明变量记录总金额
        BigDecimal totalAmount = new BigDecimal("0");

//        D. 遍历所有的购物像， 一个购物项就是一个订单明细， 组装订单明细数据, 批量保存订单明细
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCartList) {
            //按下alt+enter
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setId(UUIDUtils.getUUIDInOrderId().longValue()); //订单项目的主键
            orderDetail.setName(shoppingCart.getName());  //购物项的菜品的名字
            orderDetail.setOrderId(orderId); //订单项所属的订单的id
            orderDetail.setDishId(shoppingCart.getDishId()); //购物项的菜品的id
            orderDetail.setSetmealId(shoppingCart.getSetmealId()); //购物项的套餐的id
            orderDetail.setDishFlavor(shoppingCart.getDishFlavor()); //口味
            orderDetail.setNumber(shoppingCart.getNumber());  //数量
            orderDetail.setAmount(shoppingCart.getAmount()); //单价
            orderDetail.setImage(shoppingCart.getImage()); //
            //计算每一个购物项的总价
            BigDecimal amount = shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber() + ""));
            totalAmount = totalAmount.add(amount);
            orderDetailList.add(orderDetail);
        }

//        E. 组装订单数据, 批量保存订单数据
        orders.setId(orderId);
        orders.setNumber(String.valueOf(orderId)); //订单号
        orders.setStatus(1); //状态
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setAmount(totalAmount);
        orders.setUserName(user.getName());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        orders.setCheckoutTime(LocalDateTime.now());

        //插入订单
        orderMapper.save(orders);
        //批量插入订单项
        orderDetailMapper.saveBatch(orderDetailList);


//        F. 删除当前用户的购物车列表数据
        shoppingCartMapper.clean(userId);


    }

    /**
     * 最新订单与历史订单查看功能
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public R<Page<OrdersDto>> userPage(Integer page, Integer pageSize) {
        PageHelper.startPage(page,pageSize);

        List<Orders> ordersList =  userMapper.userPage(page,pageSize);

        List<OrdersDto> ordersDtoList = ordersList.stream().map(orders -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(orders, ordersDto);
            List<OrderDetail> orderDetails = orderDetailMapper.findById(ordersDto.getId());
            ordersDto.setOrderDetails(orderDetails);
            //ordersDto.setSumNum(orderDetails.size());
            return ordersDto;
        }).collect(Collectors.toList());


        PageInfo<OrdersDto> ordersPageInfo = new PageInfo<>(ordersDtoList);


        //总页数,前端需要传入总页数
        long pages = ordersPageInfo.getPages();
        /*if (count % page == 0){
            pages = count / pageSize;
        }else {
            pages = (count / pageSize)+1;
        }*/

        Page<OrdersDto> ordersPage = new Page<>(ordersPageInfo.getList(), ordersPageInfo.getTotal(),pages);
        return R.success(ordersPage);
    }

    /**
     * 订单明细功能
     * @param page
     * @param pageSize
     * @param number    订单号
     * @param beginTime 头时间
     * @param endTime   尾时间
     * @return
     */
    @Override
    public R<Page<Orders>> page(Integer page, Integer pageSize, Long number, Date beginTime, Date endTime) {
        PageHelper.startPage(page,pageSize);

        List<Orders> ordersList = userMapper.page(number,beginTime,endTime);

        PageInfo<Orders> ordersPageInfo = new PageInfo<>(ordersList);

        Page<Orders> ordersPage = new Page<>(ordersPageInfo.getList(), ordersPageInfo.getTotal());

        return R.success(ordersPage);

    }
}
